package com.example.administrator.basedemos.okhttp;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;

import org.json.JSONException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * 创建者     ZCL
 * 创建时间   2018/3/14 20:32
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class OkhttpManger {

    private static OkhttpManger mInstance;
    private        OkHttpClient mOkHttpClient;
    private   Handler      mHandler;
    private  Gson mGson;

    public OkhttpManger() {
        initOkhttpClient();
        mHandler = new Handler(Looper.getMainLooper());
        mGson = new Gson();
    }

    /**
     * c初始化okhtttpclient
     */
    private void initOkhttpClient() {
        mOkHttpClient = new OkHttpClient()
                .newBuilder()
                .readTimeout(30000, TimeUnit.MILLISECONDS)
                .connectTimeout(30000, TimeUnit.MILLISECONDS)
                .build();
    }

    /**
     * 创建单例对象
     */
    public static synchronized OkhttpManger getInstance() {
        if (mInstance == null)
            mInstance = new OkhttpManger();
        return mInstance;
    }

    /**
     * 请求数据进行桥接
     * 讲resquest，basecallback从搭建的框架内传递过来
     * 将baseCallback与okhttp的callback进行对接
     * 用callback将需要的现实出来
     *
     * 桥接完毕去实现request
     */
    public void reuqest(SimpleOkhttpClient client, final BaseCallBack callBack) {

        try {
            mOkHttpClient.newCall(client.builderRequest()).enqueue(new Callback() {
                @Override
                public void onFailure(final Call call, final IOException e) {
                    sendFailMessage(call, e, callBack);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String body = response.body().string();
                        //如果類型為空或者類型為string則直接發送數據
                        if (callBack.mType == null || callBack.mType == String.class) {
                            sendSuccessMessage(callBack, body);
                        }else {
                            sendSuccessMessage(callBack, mGson.fromJson(body, callBack.mType));
                        }
                    } else
                        sendErrorMessage(callBack, response.code());

                    if(response.body()!=null)
                        response.body().close();

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求出错
     *
     * @param callBack
     * @param code
     */
    private void sendErrorMessage(BaseCallBack callBack, int code) {
        callBack.onError(code);
    }

    /**
     * 请求成功
     * 转换成需要的类型
     *
     * @param callBack
     * @param body
     */
    private void sendSuccessMessage(BaseCallBack callBack, Object body) {
        callBack.onSuccess(body);
    }

    /**
     * 请求失败
     *
     * @param call
     * @param e
     * @param callBack
     */
    private void sendFailMessage(final Call call, final IOException e, final BaseCallBack callBack) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onFaile(call, e);
            }
        });
    }

}
